<template>
  <div class="search">
    <van-nav-bar title="商品搜索" left-arrow @click-left="$router.go(-1)" />

    <van-search
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
      clearable
    >
      <template #action>
        <div @click="handelSearch(value)">搜索</div>
      </template>
    </van-search>

    <!-- 搜索历史 -->
    <div class="search-history">
      <div class="title">
        <span>最近搜索</span>
        <van-icon name="delete-o" size="16" @click="clearHis" />
      </div>
      <div class="list">
        <div
          class="list-item"
          v-for="(item, index) in searchData"
          :key="index"
          @click="$router.push(`/searchlist?search=${item}`)"
        >
          {{ item }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getHistoryList, removeInfo, setHistoryList } from "@/utils/storage";
export default {
  name: "SearchIndex",
  data() {
    return {
      searchData: getHistoryList(),
      value: "",
    };
  },
  mounted() {
    console.log(this.searchData);
  },
  methods: {
    // 搜索按钮
    handelSearch(key) {
      // 如果有相同的记录就不操作
      var index = this.searchData.indexOf(this.value);
      console.log(index);
      // 没有相同记录 并且 用户输入不为空值
      if (index == -1 && this.value) {
        this.searchData.unshift(this.value);
        setHistoryList(this.searchData);
        // 清空用户搜索的东西
        this.value = "";
        this.$router.push(`/searchlist?search=${key}`);
      }
      
    },

    // 清除搜索记录
    clearHis() {
      removeInfo("hm_shoping_history");
      this.searchData = [];
    },
  },
};
</script>

<style lang="less" scoped>
.search {
  .searchBtn {
    background-color: #fa2209;
    color: #fff;
  }
  ::v-deep .van-search__action {
    background-color: #c21401;
    color: #fff;
    padding: 0 20px;
    border-radius: 0 5px 5px 0;
    margin-right: 10px;
  }
  ::v-deep .van-icon-arrow-left {
    color: #333;
  }
  .title {
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 15px;
  }
  .list {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    padding: 0 10px;
    gap: 5%;
  }
  .list-item {
    width: 30%;
    text-align: center;
    padding: 7px;
    line-height: 15px;
    border-radius: 50px;
    background: #fff;
    font-size: 13px;
    border: 1px solid #efefef;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-bottom: 10px;
  }
}
</style>